<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
      <el-row>
        <!-- <el-col :span="24">
          <el-form-item label="文件名称" prop="name" class="mt-10px">
            <el-input readonly placeholder="文件上传自动填写" v-model="formData.name" />
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="发文年份" prop="year" class="mt-10px">
            <el-date-picker
              v-model="formData.year"
              class="!w-100%"
              type="year"
              value-format="YYYY"
              placeholder="请选择年份"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="发文来源" prop="source">
            <!-- <el-input placeholder="请输入来源" v-model="formData.source" /> -->
            <el-select v-model="formData.source" placeholder="请选择来源">
              <el-option v-for="item in sourceList" :key="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="发文单位" prop="deptId">
            <el-input placeholder="请输入单位" v-model="formData.deptId" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传附件" prop="fileId" style="margin-bottom: 10px">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              multiple
              :limit="1"
              class="upload-demo"
              action=""
              :auto-upload="false"
              :before-remove="beforeRemove"
              :on-remove="handleRemove"
              :on-error="handleError"
              :on-exceed="handleExceed"
              accept=".doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.pdf,.jpg,.jpeg,.png,.zip,.rar,.7z"
              :on-change="handleChange"
            >
              <el-tooltip placement="right" max-width="300">
                <template #content>
                  <div>
                    <div>支持上传以下格式：</div>
                    <div>• 文档类：doc/docx、ppt/pptx、xls/xlsx、txt、pdf</div>
                    <div>• 图片类：jpg/jpeg、png</div>
                    <div>• 压缩包：zip、rar、7z</div>
                    <div class="text-xs mt-1">最多一个文件，大小不超过 100 MB</div>
                  </div>
                </template>
                <el-button type="primary" plain>
                  <Icon class="mr-5px" icon="ep:upload-filled" />
                  选取文件
                </el-button>
              </el-tooltip>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as IctApi from '@/api/project/ict'
import * as KmsApi from '@/api/project/kms'
import { FormRules } from 'element-plus'
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('上传文件') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = reactive({
  name: '',
  year: '',
  source: '',
  deptId: '',
  fileId: ''
})
const fileList = ref([]) // 绑定的文件列表
const sourceList = ref(['国家', '行业', '集团', '陕西公司'])

const uploadRef = ref()
const formRules = reactive<FormRules>({
  // name: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }],
  year: [{ required: true, message: '发文年份不能为空', trigger: 'blur' }],
  source: [{ required: true, message: '文件来源不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '发文部门不能为空', trigger: 'blur' }],
  fileId: [{ required: true, message: '上传附件不能为空', trigger: 'blur' }]
})

const emit = defineEmits(['success', 'getProjectInfo'])
const formRef = ref()

// 文件列表移除文件提示
const beforeRemove = (uploadFile) => {
  return ElMessageBox.confirm(`取消上传文件 ${uploadFile.name} 吗?`).then(
    () => true,
    () => false
  )
}

// 上传错误提示
const handleError = () => {
  ElMessage.error('导入文件失败，请您重新上传！')
}

// 删除上传文件
const handleRemove = (file) => {
  const index = fileList.value.map((f) => f.name).indexOf(file.name)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
}

//限制数量
const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `您本次选择了 ${files.length} 个文件, 当前共 ${
      files.length + uploadFiles.length
    } 个文件，最多可上传1个文件`
  )
}

// 上传文件限制格式、大小和当次不能重复
const handleChange = (uploadFile, uploadFiles) => {
  let fileSize = Number(uploadFile.size / 1024 / 1024)

    // 定义允许的文件类型
    const allowedFileTypes = [
    'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt', 'pdf',
    'jpg', 'jpeg', 'png', 'zip', 'rar', '7z'
  ];

  // 获取文件扩展名
  const extension = uploadFile.name.split('.').pop().toLowerCase();
  
  // 验证文件类型
  // 验证文件类型
  if (!allowedFileTypes.includes(extension)) {
    ElMessage.error('不支持的文件格式，请上传正确格式的文件');
    // 从文件列表中移除不符合格式的文件
    const index = uploadFiles.findIndex(file => file.uid === uploadFile.uid);
    if (index !== -1) {
      uploadFiles.splice(index, 1);
    }
    fileList.value = [...uploadFiles];
    return;
  }

  if (fileSize > 100) {
    ElMessage.warning('文件大小不能超过100MB，请您重新上传！')
    const index = fileList.value.map((f) => f.name).indexOf(uploadFile.name)
    if (index > -1) {
      fileList.value.splice(index, 1)
    }
    return
  }
  fileList.value = uploadFiles
  if (
    fileList.value.findIndex((f) => f.name === uploadFile.name) !=
    fileList.value.findLastIndex((f) => f.name === uploadFile.name)
  ) {
    ElMessage.info(uploadFile.name + ' 文件已存在!')
    fileList.value.pop()
  }
}

// 文件上传
const uploadFile = async (file) => {
  const uploadData = new FormData()
  uploadData.append('resource_name', formData.name || '')
  uploadData.append('resource_id', '')
  uploadData.append('file_type', '制度库')
  uploadData.append('file', file)
  try {
    const response = await KmsApi.uploadFile(uploadData)
    return response
  } catch (error) {
    console.error('File upload error:', error)
    throw error
  }
}

// 打开弹窗
const open = async () => {
  resetForm()
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const submitForm = async () => {
  // 上传所有文件
  const fileIds = []
  for (const file of fileList.value) {
    const fileId = await uploadFile(file.raw)
    fileIds.push(fileId)
  }
  formData.fileId = fileIds[0]
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formData.name = fileList.value[0].name
  ElMessageBox.confirm(`确认上传制度文件【${formData.name}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 提交请求
      formLoading.value = true
      try {
        if (dialogTitle.value === '上传文件') {
          await IctApi.createFile(formData)
          ElMessage.success('上传成功！')
          // 重置表单
          resetForm()
          fileList.value = []
          uploadRef.value.clearFiles()
        }
        dialogVisible.value = false
        //发送操作成功的事件
        emit('success', true)
      } finally {
        formLoading.value = false
      }
    })
    .catch(() => {
      ElMessage.info('已取消上传')
    })
}

// 重置表单
const resetForm = () => {
  formData.deptId = ''
  formData.fileId = ''
  formRef.value?.resetFields()
}
</script>
<style lang="scss" scoped>
:deep(.el-upload--picture-card) {
  background: #fff;
}
.limitStyle {
  font-size: 12px;
  color: rgb(246 132 132);
  line-height: 16px;
}
</style>
